import React, { useMemo, useState, createContext, useEffect } from "react";
import { View } from "@tarojs/components";
import { NoData } from "..";

interface PageProps {
  request?: (...param: any[]) => Promise<any>;
  // 删除字段别名key value
  deleteField?: { key: string; value: string | number };
  // 下架字段名称
  offField?: { key: string; value: string | number };
}

// 创建 Context
const PageContext = createContext<any>(null);
export const usePageContext = () => React.useContext(PageContext);
const PageView: React.FC<PageProps> = ({
  request,
  deleteField,
  offField,
  ...props
}) => {
  const [detailInfo, setDetailInfo] = useState({});

  useEffect(() => {
    if (request) {
      request().then((res) => {
        setDetailInfo(res);
      });
    }
  }, [request]);
  // 是否下架或者删除
  const isOffDelete = () => {
    // 如果已经下架了
    if (deleteField) {
      return detailInfo[deleteField.key] === deleteField.value;
    }
    // 如果已经删除了
    if (offField) {
      return detailInfo[offField.key] === offField.value;
    }
    if (detailInfo.status === 0) {
      return true;
    }
    // 默认没有下架或者删除
    return false;
  };

  const renderContent = () => {
    if (isOffDelete()) {
      return <NoData />;
    }
    return <View>{props.children}</View>;
  };

  return (
    <PageContext.Provider value={{ detailInfo, setDetailInfo }}>
        {renderContent()}
    </PageContext.Provider>
  );
};

export default PageView;
